using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Cou;
using net_work.Data.Entity.Cou;
using net_work.Data.Enum.Cou;
using net_work.IRepository.Cou;
using net_work.IService.Cou;

namespace net_work.Service.Cou;

public class ScheduleService(IScheduleRepository scheduleRepository, ITeachingRepository teachingRepository)
    : IScheduleService
{
    public Task<PagedResult<Schedule>> GetSchedulesPagedAsync(PagedRequest request)
    {
        return scheduleRepository.GetPagedAsync(request);
    }

    public Task<Schedule?> SelectByIdAsync(long scheduleId)
    {
        return scheduleRepository.GetByIdAsync(scheduleId);
    }

    public async Task<long> InsertSchedule(ScheduleAddRequest scheduleAddRequest)
    {
        var teaching = await teachingRepository.GetByIdAsync(scheduleAddRequest.TeachId);
        if (teaching == null)
        {
            return -1;
        }

        if (teaching.TeachStatus == TeachStatus.Release)
        {
            return -1;
        }

        return await scheduleRepository.InsertAsync(scheduleAddRequest);
    }

    public async Task<int> UpdateSchedule(ScheduleUpdateRequest scheduleUpdateRequest)
    {
        if (scheduleUpdateRequest.Id <= 0)
        {
            return -1;
        }

        var teaching = await teachingRepository.GetByIdAsync(scheduleUpdateRequest.TeachId);
        if (teaching == null)
        {
            return -1;
        }

        if (teaching.TeachStatus == TeachStatus.Release)
        {
            return -1;
        }

        return await scheduleRepository.UpdateAsync(scheduleUpdateRequest) ? 1 : -1;
    }

    public async Task<int> DeleteScheduleByIds(List<long> ids)
    {
        foreach (var id in ids)
        {
            var schedule = await scheduleRepository.GetByIdAsync(id);
            if (schedule == null)
            {
                continue;
            }

            var teaching = await teachingRepository.GetByIdAsync(schedule.TeachId);
            if (teaching == null)
            {
                return -1;
            }

            if (teaching.TeachStatus == TeachStatus.Release)
            {
                return -1;
            }
        }

        return await scheduleRepository.DeleteByIdsAsync(ids) ? 1 : -1;
    }
}